package lancoo.com.net.retrofitrxjava.download;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


public class UpLoadPart {
    public static UpLoadPart mUpLoadPart;
    private final String MEDIATYPE_IMG="image/jpeg";
    private final String MEDIATYPE_UNIMG="multipart/form-data;charset=UTF-8";

    public static UpLoadPart getInstance(){
        if(mUpLoadPart==null){
            synchronized (UpLoadPart.class){
                mUpLoadPart=new UpLoadPart();
            }
        }
        return mUpLoadPart;
    }

    /**
     *
     * @param file 需上传的本地文件
     * @param serviceFileName 上传到服务器所定义的名称
     * @param isImg 文件是否是图片格式
     * @param uploadProgressListener 上传时的回调监听
     * @return
     */
    public MultipartBody.Part getPart(File file,String serviceFileName,boolean isImg,UploadProgressListener uploadProgressListener){
        RequestBody requestBody=RequestBody.create(MediaType.parse(isImg?MEDIATYPE_IMG:MEDIATYPE_UNIMG),file);
        ProgressRequestBody progressRequestBody=new ProgressRequestBody(requestBody,uploadProgressListener);
        MultipartBody.Part part = MultipartBody.Part.createFormData(serviceFileName, file.getName(), progressRequestBody);
         return part;
    }

    /**
     *
     * @param file 需上传的本地文件
     * @param serviceFileName 上传到服务器所定义的名称
     * @param isImg 文件是否是图片格式
     * @param uploadProgressListener 上传时的回调监听
     * @return
     */
    public MultipartBody.Part getPart(String userID,File file,String serviceFileName,boolean isImg,UploadProgressListener uploadProgressListener){
        MultipartBody.Builder builder=new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        String params="{\"UserID\":\"123\"}";
        RequestBody requestBody=RequestBody.create(MediaType.parse(isImg?MEDIATYPE_IMG:MEDIATYPE_UNIMG),file);
        RequestBody requestBody1=RequestBody.create(MediaType.parse("application/json; charset=utf-8"),params);
//        builder.addFormDataPart(serviceFileName, file.getName(), requestBody);
        builder.addPart(requestBody1);
        MultipartBody build = builder.build();
        ProgressRequestBody progressRequestBody=new ProgressRequestBody(build,uploadProgressListener);

        MultipartBody.Part part = MultipartBody.Part.createFormData(serviceFileName, file.getName(), progressRequestBody);
        return part;
    }

    public Map<String,RequestBody> getMapRequestBodyByFile(List<File> files,UploadProgressListener uploadProgressListener){
        Map<String,RequestBody> map=new HashMap<>() ;
        for (File file:files){
            RequestBody requestBody=RequestBody.create(MediaType.parse(MEDIATYPE_IMG),file);
//            ProgressRequestBody progressRequestBody=new ProgressRequestBody(requestBody,uploadProgressListener);
            map.put("file1",requestBody);
        }
        return map;
    }

}
